﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.DAO;
using SCRUM.Core.BusinessObjects;

/// <summary>
/// Widget showing users in specified project/team and role.
/// </summary>
public partial class UserManagement : DataOverviewWidget<User> //WidgetBase
{
    #region [ USERMANAGEMENTWIDGET ]

    private IList<User> users;

    /// <summary>
    /// Number of columns (from left) which are always displayed
    /// </summary>
    private int userColumnsOffset = 1;

    /// <summary>
    /// Array of available columns in GridView which can/cannot be displayed
    /// </summary>
    //private string[] userColumns = { "Fullname", "Email", "Telephone", "IM", "Enabled", "DefaultRole" };

    #endregion

    /// <summary>
    /// Gets the name of the widget. It must be exactly the same as the folder that contains the widget.
    /// </summary>
    /// <value></value>
    public override string Name
    {
        get { return "UserManagement"; }
    }

    /// <summary>
    /// Gets the title. Title is shown in the header of the widget container.
    /// </summary>
    /// <value>The title.</value>
    public override string Title
    {
        get { return (string)GetLocalResourceObject("Title"); } 
    }

    #region [UserManagementWidget Settings]

    /// <summary>
    /// Gets a value indicating whether this instance is editable.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this instance is editable; otherwise, <c>false</c>.
    /// </value>
    public override bool IsEditable
    {
        get { return true; }
    }

    /// <summary>
    /// Shows the edit.
    /// </summary>
    public override void ShowEdit()
    {
        base.ShowEdit();
        this.EditUserManagementWidget.Visible = true;
    }

    /// <summary>
    /// Hides the edit.
    /// </summary>
    public override void HideEdit()
    {
        base.HideEdit();
        this.EditUserManagementWidget.Visible = false;
    }

    /// <summary>
    /// Occurs when user clicks on Save Settings of PrototypeWidget
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SaveSettingsClick(object sender, EventArgs e)
    {
        SaveSettings();
        this.HideEdit();
        LoadWidget();
    }

    /// <summary>
    /// Refreshes settings section with data from private member settings
    /// </summary>
    private void ShowSettings()
    {
        LabelPageSize.Text = settings["pageSize"];
    }

    #endregion

    /// <summary>
    /// Sets handlers for events.
    /// </summary>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected override void OnInit(EventArgs e)
    {
        this.itemDetails.PasswordChangeSuccessEvent += new EventHandler(PasswordChangedSuccess);
        GridViewData.PageIndexChanging += new GridViewPageEventHandler(GridViewData_SelectedPageChanged);
    }

    /// <summary>
    /// This method works as a substitute for Page_Load. You should use this method for
    /// data binding etc. instead of Page_Load.
    /// </summary>
    public override void LoadWidget()
    {
        LoadAvailableColumns();
        ApplySettings();
        if (!IsPostBack)
        {
            RefreshWidget();
        }
    }

    /// <summary>
    /// Applies the filter.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ApplyFilter(object sender, EventArgs e)
    {
        //LoadData();
        GridViewData.SelectedIndex = -1;
        this.itemDetails.Visible = false;
        HideButtons();
        RefreshWidget();
        //loadUsers();
    }

    /// <summary>
    /// Clears the filter.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ClearFilter(object sender, EventArgs e)
    {
        //this.TeamSelectionTeam.Clear();
        //this.SingleRoleSelectionRoles.Clear();
        //LoadData();
        GridViewData.SelectedIndex = -1;
        this.itemDetails.Visible = false;
        HideButtons();
        ClearTextBoxes();
        //loadUsers();
        RefreshWidget();
    }

    private void ClearTextBoxes()
    {
        Login.Text = string.Empty;
        Fullname.Text = string.Empty;
        Email.Text = string.Empty;
    }

    /// <summary>
    /// Called when [row data bound].
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        User user = e.Row.DataItem as User;
        if (user != null)
        {
            ((YesNoInfo)e.Row.FindControl("YesNo")).Value = user.Enabled;
            HyperLink emailHyperlink = (HyperLink)e.Row.FindControl("HyperlinkEmail");
            emailHyperlink.NavigateUrl = String.Format("mailto:{0}", user.Email);
            emailHyperlink.Text = user.Email;
        }
    }

    #region [ DATA CONTROLS ]

    /// <summary>
    /// Create new user.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonCreate_Click(object sender, EventArgs e)
    {
        this.itemDetails.SelectedItem = null;
        this.itemDetails.Visible = true;
        this.itemDetails.ShowPasswordArea();
        this.itemDetails.HideImageKey();
        this.buttonCreateItem.Visible = true;
        this.buttonCancelItem.Visible = true;
        //haveToShowItemDetails = true;
        this.buttonSaveItem.Visible = false;
        this.buttonDeleteItem.Visible = false;
    }

    /// <summary>
    /// Raises when user wants to Create new User
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ButtonCreateItem_Click(object sender, EventArgs e)
    {
        try
        {
            User newUser = this.itemDetails.CreateItem();
            DAODashboardLayout.CreateDefaultLayout(newUser);
            this.ShowOperationResult(MessageType.Info, "UserCreated");            
        }
        catch
        {
            this.ShowOperationResult(MessageType.Error, "UserNotCreated");
        }
        RefreshWidget();
        //RefreshWidget();
        this.itemDetails.Visible = false;
        HideButtons();
    }

    /// <summary>
    /// Raises when user wants to Save existing User
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ButtonSaveItem_Click(object sender, EventArgs e)
    {
        this.itemDetails.EditItem(this.selectedItem.ID);
        RefreshWidget();
        this.itemDetails.Visible = false;
        HideButtons();
    }

    /// <summary>
    /// Raises when user wants to cancel editting User
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ButtonCancelItem_Click(object sender, EventArgs e)
    {
        HideButtons();
        this.itemDetails.Visible = false;
    }

    /// <summary>
    /// Raises when user wants to delete existing User
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ButtonDeleteItem_Click(object sender, EventArgs e)
    {
        //UserDetails.DeleteItem(UserDetails.SelectedItem);
        this.itemDetails.DeleteItem(this.selectedItem);
        //loadUsers();
        this.itemDetails.Visible = false;
        HideButtons();
        RefreshWidget();
    }

    private void HideButtons()
    {
        this.buttonCreateItem.Visible = false;
        this.buttonSaveItem.Visible = false;
        this.buttonCancelItem.Visible = false;
        this.buttonDeleteItem.Visible = false;
    }
    /// <summary>
    /// User click on some user in Gridview
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected override void GridViewData_SelectedIndexChanged(object sender, EventArgs e)
    {
        base.GridViewData_SelectedIndexChanged(sender, e);
        //SelectUser(selectedItem);
        //UserDetails.Visible = true;
        //SelectSprint(GridViewData.SelectedIndex);
        //haveToShowItemDetails = SprintDetail.SelectedItem != null;
        //this.ButtonCreateItem.Visible = false;
    }

    ///// <summary>
    ///// Selects the sprint specified by position in all sprints
    ///// Displays sprint details, shows/hides delete button
    ///// </summary>
    ///// <param name="sprintPos">The sprint pos.</param>
    //private void SelectUser(int userPos)
    //{
    //    this.UserDetails.SelectedItem = (userPos == -1) ? null : users[userPos];
    //    UserDetails.Visible = true;
    //    this.ButtonSaveItem.Visible = true;
    //    this.ButtonDeleteItem.Visible = true;
    //    this.ButtonCancelItem.Visible = true;
    //    //haveToShowItemDetails = UserDetails.SelectedItem != null;
    //}

    #endregion

    /// <summary>
    /// Passwords changed successfully.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void PasswordChangedSuccess(object sender, EventArgs e)
    {
        this.ShowOperationResult(MessageType.Info, "PasswordChanged");
    }

    /// <summary>
    /// Passwords change failed.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void PasswordChangedFail(object sender, EventArgs e)
    {
        this.ShowOperationResult(MessageType.Error, "PasswordNotChanged");
    }

    public override void RefreshWidget()
    {
        base.RefreshWidget();
        bool itemSelected = this.data.SelectedIndex != -1;
        SelectAndDisplayItem(this.selectedItem, itemSelected);
        //this.buttonCreate.Visible = this.filtersSuperiorItemID != -1 && this.UserRights.CanModify;
    }

    /// <summary>
    /// Sets visibility of detail of item and buttons to create, edit, delete and cancel in form
    /// </summary>
    /// <param name="item">Type of item to dislay</param>
    /// 
    /// <param name="show">If detail should be displayed</param>
    /// 
    protected void SelectAndDisplayItem(User item, bool show)
    {
        bool exists = item != null;
        this.itemDetails.SelectedItem = item;
        this.itemDetails.Visible = show;
        //this.buttonCreateItem.Visible = show && !exists && this.UserRights.CanModify;
        //this.buttonSaveItem.Visible = show && exists && this.UserRights.CanModify;
        //this.buttonDeleteItem.Visible = show && exists && this.UserRights.CanModify;
        this.buttonCreateItem.Visible = show && !exists;
        this.buttonSaveItem.Visible = show && exists;
        this.buttonDeleteItem.Visible = show && exists;
        this.buttonCancelItem.Visible = show;
    }

    protected override IList<User> itemsAcordingToFilter
    {
        get 
        {
            string login = Login.Text != string.Empty ? Login.Text : null;
            string fullname = Fullname.Text != string.Empty ? Fullname.Text : null;
            string email = Email.Text != string.Empty ? Email.Text : null;
            return DAOUser.GetUsers(-1, login, fullname, email, null, null, null, -1);
        }
    }

    protected override int alwaysVisibleColumn
    { get { return 0; }
    }

    protected override GridView data
    {
        get { return this.GridViewData; }
    }

    protected override Panel availableColumnsPanel
    {
        get { return this.AvailableColumns; }
    }

    protected override TextBox textBoxPageSize
    {
        get { return this.TextBoxPageSize; }
    }

}
